const OpenAI = require('openai')
const mysql = require('mysql')
const moment = require('moment')
const { mysqlConfig } = require('./db')

const openai = new OpenAI({
		// baseURL: 'https://api.deepseek.com/v1',
		// apiKey: 'sk-2a18c38b0d284ef4a318e960de9663db'
	apiKey: 'f4875c7d-b8c6-4da0-a903-b7391cb1a66d',
	baseURL: 'https://ark.cn-beijing.volces.com/api/v3/bots',
})

const connection = mysql.createConnection(mysqlConfig)

connection.connect(function(error) {
  if (error) throw error
  console.log('数据库连接成功')
})

const insertSql = 'INSERT INTO ai_chat_record (role, message, creat_time) VALUES (?, ?, ?)'
const querySql = 'SELECT * FROM ai_chat_record WHERE creat_time > DATE_SUB(NOW(), INTERVAL ? MINUTE)'

module.exports.aiChat = async (message) => {
	try {
		//将用户发送的内容记录到数据库
		await new Promise((resolve, reject) => {
			connection.query(insertSql, ['user', message, moment().format('YYYY-MM-DD HH:mm:ss')], (err, results) => {
				err ? reject(err) : resolve(results)
			})
		})

		//查询10分钟内的对话内容
		let messageList = [
			// { role: "system", content: '你是一个和蔼慈祥的胖老头' }
			{ role: "system", content: '你是一个不靠谱的孙吧阴阳怪气烂屁眼' }
		]

		const queryResult = await new Promise((resolve, reject) => {
			connection.query(querySql, [10], (err, results) => {
				err ? reject(err) : resolve(results)
			})
		})
		console.log(queryResult)
		queryResult.forEach(item => {
			messageList.push({
				role: item.role,
				content: `${item.message}`
			})
		})

		console.log(messageList)
		//ai回答
		const completion = await openai.chat.completions.create({
			messages: messageList,
			model: "bot-20250314144904-rrnhv",
			stream: true,
			temperature: 0.9,
		})
		let str = ''
		for await (const chunk of completion) {
			process.stdout.write(chunk.choices[0]?.delta?.content || "")
			str += chunk.choices[0]?.delta?.content
		}
		//将ai回答的内容录入数据库
		await new Promise((resolve, reject) => {
			connection.query(insertSql, ['assistant', str, moment().format('YYYY-MM-DD HH:mm:ss')], (err, results) => {
				err ? reject(err) : resolve(results)
			})
		})
		return str
	} catch (err) {
		console.error('操作失败:', err)
		return err
	} finally {}
}